import axios from 'axios'
let state = false

let eleFile = null

// 缩放图片需要的元素和对象 ,因为考虑到服用。所以这些东西都需要单独的实例
// let reader = null
// let img = null

// 选择的文件对象
let file = null

// 缩放图片需要的canvas
let canvas = null
let context = null

// 最大尺寸限制
const maxwidth = 400
const maxHeight = 400

let targetWidth = null
let targetHeight = null

export default {
  _init: function () {
    canvas = document.createElement('canvas')
    context = canvas.getContext('2d')

    state = true
    console.log('内部初始化成功')
  }, // 内部初始化

  init: function (ele, url, callback) {
    // 判断第三个参数是否为函数
    if (typeof callback !== 'function') {
      // throw 'callback must be a function'
      console.error('callback must be a function')
      return
    }

    if (state) {
      console.log('脚本已加载,跳过内部初始化')
    } else {
      this._init()
    }

    eleFile = ele
    let reader = new FileReader()
    let img = new Image()
    img.onload = function () {
      // 图片原始尺寸
      let originWidth = this.width
      let originHeight = this.height

      // 目标尺寸
      targetWidth = originWidth
      targetHeight = originHeight

      // 图片尺寸超过限制
      if (originWidth > maxwidth || originHeight > maxHeight) {
        if (originWidth / originWidth > maxwidth / maxHeight) {
          // 更宽，按照宽度限定尺寸
          targetWidth = maxwidth
          targetHeight = Math.round(maxwidth * (originHeight / originWidth))
        } else {
          targetHeight = maxHeight
          targetWidth = Math.round(maxHeight * (originWidth / originHeight))
        }
      }

      // canvas对图片进行缩放
      canvas.width = targetWidth
      canvas.height = targetHeight

      // 清除画布
      context.clearRect(0, 0, targetWidth, targetHeight)

      // 图片压缩
      context.drawImage(img, 0, 0, targetWidth, targetHeight)

      // canvas转为blob并上传
      canvas.toBlob(function (blob) {
        let fromData = new FormData()
        fromData.append('upfile', blob, 'demo.jpg')
        axios({
          method: 'post',
          url,
          data: fromData
        })
          .then(function (response) {
            // 在回调函数中进行照片显示
            callback(response.data)
          })
      }, file.type || 'image/png')
    }

    // 文件base64化，方便知道图片原始尺寸
    reader.onload = function (e) {
      img.src = e.target.result
    }

    eleFile.addEventListener('change', function (event) {
      file = event.target.files[0]
      // 选择的文件是图片
      if (file.type.indexOf('image') === 0) {
        reader.readAsDataURL(file)
      }
    })
    console.log('实例化成功，表单元素为：', eleFile)
  }
}
